<template>
	<view class="log-container">
		<!-- 顶部标题 -->
		<view class="header">
			<text class="title">ATM 管理日志</text>
		</view>

		<!-- 筛选区域 -->
		<view class="filter-card">
			<!-- 日期范围 -->
			<view class="form-item">
				<text class="label">日期范围：</text>
				<uni-datetime-picker v-model="datetimerange" type="datetimerange" :start="startDate" :end="endDate"
					rangeSeparator="至" class="datetime-style" />
				<view v-if="datetimerange && datetimerange.length === 2" class="display-range">
					{{ formatRange(datetimerange) }}
				</view>
			</view>

			<!-- 区域选择 -->
			<view class="form-item">
				<text class="label">区域：</text>
				<uni-data-select v-model="selectedArea" :localdata="areaOptions" class="select-style" />
			</view>

			<!-- 标签选择 -->
			<view class="tag-filter">
				<view v-for="(tag, index) in tagsOptions" :key="index" class="tag-item" :class="{
            active: selectedTags.includes(tag.value),
            disabled: isTagDisabled(tag.value)
          }" @click="!isTagDisabled(tag.value) && toggleTag(tag.value)">
					{{ tag.text }}
					<view v-if="isTagDisabled(tag.value)" class="slash">/</view>
				</view>
			</view>
		</view>


		<!-- 查询按钮 -->
		<view style="padding: 20rpx; text-align:center;">
			<button class="search-btn" @click="onSearch"> 查询</button>
		</view>



		<!-- 日志列表 -->
		<scroll-view scroll-y class="log-list" @scrolltolower="loadMore">
			<view v-for="(item, idx) in filteredLogs" :key="idx" class="log-card" @click="openLogDetail(item)">
				<view class="log-header">
					<text class="log-type">{{ item.type }}</text>
					<view class="log-meta">
						<text class="log-time">{{ item.time }}</text>
						<text class="area-badge">{{ item.details["区域"] }}</text>
					</view>
				</view>
				<view class="log-body">
					<text v-for="(val, key) in item.details" :key="key" class="log-detail">
						{{ key }}: {{ val }}
					</text>
				</view>
			</view>
		</scroll-view>



		<!-- 日志详情弹窗 -->
		<uni-popup ref="logDetailPopup" type="center">
			<view class="popup-content">
				<text class="popup-title">{{ selectedLog?.type || '' }} - {{ selectedLog?.time || '' }}</text>
				<view class="popup-details">
					<view v-for="(val, key) in selectedLog?.details || {}" :key="key">
						{{ key }}: {{ val }}
					</view>
				</view>
				<button @click="closeLogDetail">关闭</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getOperationLog
	} from '@/api/user';

	export default {
		data() {
			return {
				datetimerange: [],
				startDate: "2021-01-01 00:00:00",
				endDate: "2026-12-31 23:59:59",

				selectedArea: "南区",
				areaOptions: [{
						text: "南区",
						value: "南区"
					},
					{
						text: "北区",
						value: "北区"
					},
					{
						text: "离岛",
						value: "离岛"
					},
					{
						text: "全部",
						value: "全部"
					},
				],

				page: 1,
				pageSize: 5,
				logs: [],
				selectedLog: null,

				tagsOptions: [{
						value: "存款取款",
						text: "存款/取款"
					},
					{
						value: "补钞",
						text: "补钞"
					},
					{
						value: "设备告警",
						text: "设备告警"
					}
				],
				selectedTags: [],

				loading: false,
				noMore: false
			};
		},

		computed: {
			filteredLogs() {
				return this.logs.filter(log => {
					// 标签过滤
					const tagMatch = this.selectedTags.length === 0 || this.selectedTags.includes(log.tag);

					// 区域过滤
					const areaMatch = !this.selectedArea || log.details["区域"] === this.selectedArea;

					// 日期过滤
					let dateMatch = true;
					if (this.datetimerange && this.datetimerange.length === 2) {
						const logTime = new Date(log.time);
						const start = new Date(this.datetimerange[0]);
						const end = new Date(this.datetimerange[1]);
						dateMatch = logTime >= start && logTime <= end;
					}

					return tagMatch && areaMatch && dateMatch;
				});
			}
		},

		async mounted() {
			this.logs = await this.fetchLogs(this.page, this.pageSize);
		},

		methods: {
			isTagDisabled(tagValue) {
				const depositTags = ["存款取款"];
				const otherTags = ["补钞", "设备告警"];
				if (this.selectedTags.includes("存款取款") && otherTags.includes(tagValue)) return true;
				if (this.selectedTags.some(t => otherTags.includes(t)) && depositTags.includes(tagValue)) return true;
				return false;
			},

			toggleTag(tagValue) {
				const depositTags = ["存款取款"];
				const selected = this.selectedTags;
				const index = selected.indexOf(tagValue);

				if (index > -1) {
					selected.splice(index, 1);
				} else {
					if (depositTags.includes(tagValue)) {
						this.selectedTags = [tagValue]; // 存款取款单选
					} else {
						this.selectedTags = selected.filter(t => !depositTags.includes(t));
						this.selectedTags.push(tagValue);
					}
				}
			},

			async fetchLogs(page, pageSize) {
				this.loading = true;

				const params = {
					page,
					pageSize,
					area: this.selectedArea === '全部' ? undefined : this.selectedArea,
					tags: this.selectedTags.length ? this.selectedTags.join(',') : undefined,
					startTime: this.datetimerange[0] ? new Date(this.datetimerange[0]).toISOString() : undefined,
					endTime: this.datetimerange[1] ? new Date(this.datetimerange[1]).toISOString() : undefined
				};

				try {
					const res = await getOperationLog(params);
					const data = res[1].data; // 或使用 Promise 封装，保证返回格式统一

					if (data && data.data.length) {
						this.loading = false;
						if (data.data.length < pageSize) this.noMore = true;
						return data.data;
					} else {
						this.noMore = true;
						this.loading = false;
						return [];
					}
				} catch (err) {
					console.error('请求日志失败', err);
					this.loading = false;
					return [];
				}
			},



			async onSearch() {
				this.page = 1;
				this.noMore = false;
				this.logs = [];
				const data = await this.fetchLogs(this.page, this.pageSize);
				this.logs = data;
			},

			async loadMore() {
				if (this.loading || this.noMore) return;
				this.page++;
				const newLogs = await this.fetchLogs(this.page, this.pageSize);
				this.logs = [...this.logs, ...newLogs];
			},


			openLogDetail(item) {
				this.selectedLog = item;
				this.$nextTick(() => this.$refs.logDetailPopup.open());
			},

			closeLogDetail() {
				this.selectedLog = null;
				this.$refs.logDetailPopup.close();
			},

			formatRange(range) {
				return `${range[0]} 至 ${range[1]}`;
			}
		},
	};
</script>

<style scoped>
	/* 容器与基础布局 */
	.log-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #fafafa;
	}

	.header {
		background-color: #bd3124;
		padding: 20rpx;
		text-align: center;
	}

	.title {
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
	}

	/* 筛选区域 */
	.filter-card {
		background: linear-gradient(135deg, #fff, #fdf3f2);
		border: 2rpx solid #f2d7d5;
		border-radius: 20rpx;
		padding: 24rpx;
		margin: 20rpx;
		box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.form-item {
		margin-bottom: 20rpx;
	}

	.label {
		font-size: 28rpx;
		margin-bottom: 10rpx;
		display: block;
		color: #444;
		font-weight: 500;
	}

	.datetime-style,
	.select-style {
		width: 100%;
		border-radius: 12rpx;
		padding: 14-16rpx;
		border: 2rpx solid #e0e0e0;
		background-color: #fff;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
	}

	.datetime-style:focus {
		border-color: #bd3124;
	}

	/* 查询按钮 */
	.search-btn {
		background-color: #bd3124;
		color: white;
		text-align: center;
		padding: 20rpx;
		border-radius: 12rpx;
		font-size: 30rpx;
		margin-top: 10rpx;
		font-weight: bold;
	}

	/* 标签样式 */
	.tag-filter {
		display: flex;
		flex-wrap: wrap;
		gap: 12rpx;
		margin: 20rpx;
	}

	.tag-item {
		padding: 12rpx 24rpx;
		border-radius: 8rpx;
		border: 1rpx solid #ccc;
		font-size: 28rpx;
		color: #666;
		background-color: #f5f5f5;
		text-align: center;
		user-select: none;
		transition: all 0.2s;
	}

	.tag-item.active {
		border-color: #bd3124;
		background-color: #bd3124;
		color: #fff;
	}

	.tag-item.disabled {
		color: #999;
		border-color: #ccc;
		cursor: not-allowed;
	}

	.tag-item .slash {
		position: absolute;
		top: 0;
		right: 4px;
		color: #999;
	}

	/* 日志列表 */
	.log-list {
		flex: 1;
		padding: 20rpx;
	}

	.log-card {
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.log-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;
	}

	.log-meta {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.log-type {
		font-weight: bold;
		color: #bd3124;
	}

	.log-time {
		font-size: 24rpx;
		color: #999;
	}

	.area-badge {
		font-size: 22rpx;
		padding: 4rpx 10rpx;
		border-radius: 10rpx;
		color: #fff;
	}

	.area-badge.南区 {
		background-color: #bd3124;
	}

	.area-badge.北区 {
		background-color: #1e90ff;
	}

	.area-badge.离岛 {
		background-color: #ff8c00;
	}

	.log-detail {
		display: block;
		font-size: 26rpx;
		color: #333;
		margin: 4rpx 0;
	}

	/* 弹窗样式 */
	.uni-popup__mask {
		background-color: rgba(0, 0, 0, 0.3);
	}

	.popup-content {
		padding: 16px;
		background: #fff;
		/* 白色为主 */
		border-radius: 8px;
		border: 1px solid #f2c7c0;
		/* 浅红点缀 */
		min-width: 280px;
		max-width: 90%;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.popup-title {
		font-weight: bold;
		font-size: 18px;
		color: #bd3124;
		margin-bottom: 12px;
	}

	.popup-details {
		font-size: 14px;
		color: #333;
		line-height: 1.6;
	}

	.popup-close {
		display: inline-block;
		margin-top: 16px;
		background: #bd3124;
		color: #fff;
		border: none;
		border-radius: 4px;
		padding: 8px 16px;
		font-weight: bold;
		text-align: center;
		cursor: pointer;
	}

	.popup-close:hover {
		background: #a72b1f;
	}

	.search-btn {
		background-color: #fff;
		/* 白色为主 */
		color: #bd3124;
		/* 银行红色文字 */
		border: 2rpx solid #bd3124;
		/* 红色边框 */
		padding: 16rpx 40rpx;
		border-radius: 12rpx;
		font-size: 28rpx;
		font-weight: bold;
		cursor: pointer;
		transition: all 0.3s;
	}

	.search-btn:hover {
		background-color: #bd3124;
		/* 悬停红色 */
		color: #fff;
		/* 悬停白字 */
	}
</style>